import {
  Controller,
  Post,
  Body,
  Get,
  Param,
  ParseIntPipe,
  Delete,
  Patch,
  Request,
  Render,
  Response,
} from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private readonly userService: UsersService) {}

  @Get()
  index(@Request() req) {
    console.log(req.session, '当前的cookie');
    return {
      title: '主页',
    };
  }

  @Get('login')
  @Render('login')
  login(
    @Response() res: { [key: string]: any },
    @Response() req: { [key: string]: any },
  ) {
    return { title: '登录页面' };
  }

  @Post('login')
  loginPage(@Body() body, @Response() res) {
    console.log(body);
    res.redirect('/user');
  }

  // /users
  @Post()
  async addUser(@Body() body: any): Promise<any> {
    return {
      code: 0,
      message: '添加用户',
      data: body,
    };
  }

  @Delete(':id')
  async delUser(@Param('id', new ParseIntPipe()) id: number): Promise<any> {
    if (id === 1) {
      return {
        code: 0,
        message: '删除成功',
      };
    }
    return {
      code: -1,
      message: '用户不存在',
    };
  }

  @Patch(':id')
  async updateUser(
    @Body() body: any,
    @Param('id', new ParseIntPipe()) id: any,
  ): Promise<any> {
    return { code: 0, body: body, id: id, message: '更新用户信息' };
  }

  // /users/1
  @Get(':id')
  async userInfo(@Param('id', new ParseIntPipe()) id: number) {
    if (id === 1) {
      return {
        code: 0,
        message: '获取用户',
      };
    }
    return {
      code: -1,
      message: '用户不存在',
    };
  }
}
